
package org.vasil.jouikov.db

import com.gmongo.GMongoClient
import com.mongodb.ServerAddress

import org.vasil.jouikov.schema.Item

class MongoService {

    static def addrs = [
        new ServerAddress('192.168.200.101', 10001), // node01
        new ServerAddress('192.168.200.102', 10001), // node02
        new ServerAddress('192.168.200.103', 10001)  // node03
//        new ServerAddress('192.168.1.200', 30001),
//        new ServerAddress('192.168.1.201', 30001),
//        new ServerAddress('192.168.1.202', 30001)
    ]
    private def db = new GMongoClient(addrs).getDB('sklad')

    def db() {
        db
    }

    // insert or update exist
    def updateItem = { item ->

        try {
            def find = db.items.findOne(['_id': item.sku], ['_id': 1])
            if(!find) {
                db.items.insert(
                    item.getItemFields() << [
                        '_id'    : item.sku,
                        'upcount': 1,
                        'created': new Date(),
                        'updated': new Date()]
                )
            }
            else {
                db.items.update(['_id': item.sku],[
                    '$set': item.getItemFields(),
                    '$inc': ['upcount': 1]
                    ]
                )
            }

            // category or nodes
            updateNodes(item)
        }
        catch(error) {
            println "MongoService:updateItem: $error"
        }
    }

    // delete exist item
    def deleteItem = { sku ->

        try {
            def doc = db.items.update(
                ['_id': sku],
                ['$set': ['active': 'D']],
                false, // upsert
                true   // multi
            )

            // pull sku from nodes
            deleteNodesSku(sku)
        }
        catch(error) {
            println "MongoService:deleteItem: $error"
        }
    }

    // delete sku from nodes
    def deleteNodesSku = { sku ->

        try {
            def docs = db.nodes.find(['nodes.sku': sku], ['nodes.sku': 1])
            println "docs=$docs"
            docs.each { doc ->
                println "_id=${doc._id}"
                doc.nodes.each { node ->
                    println "\tnode=${node.'sku'}"
                }
            }
/*
// Get only the properties we want to save 
def doctor = doc.properties.findAll { !['class', 'metaClass'].contains(it.key) }
 **/

        }
        catch(error) {
            println "MongoService:deleteNodesSku: $error"
        }
    }

    // update price
    def updateItemPrice = { item ->

        try {
//            def doc = db.nodes.find(['nodes.sku': sku], ['nodes.sku': 1])
//            println "doc=$doc"
        }
        catch(error) {
            println "MongoService:updateItemPrice: $error"
        }
    }

    // find item
    def getItem = { sku ->

        try {
            return db.items.findOne(['_id': sku])
        }
        catch(error) {
            println "MongoService:getItem: $error"
        }
    }

    // insert or update exist
    def updateNodes = { item ->

        try {
            def doc = db.nodes.findOne('nodeid': item.node.nodeid)
            //println "$doc"
            if(!doc) {
                db.nodes.insert([
                        'nodeid'    : item.node.nodeid,
                        'name'      : item.node.name,
                        'active'    : item.node.active,
                        'itemcount' : 1,
                        'nodes': [
                            item.nodes << ['itemcount': 1]
                        ]
                    ]
                )
            }
            else {
                def node = doc.nodes.find { it.nodeid == item.nodes.nodeid }
                //println "item.nodes.nodeid=${item.nodes.nodeid} node: $node"
                if(node) { // update
                    def set = [
                        'nodeid'                    : item.node.nodeid,
                        'name'                      : item.node.name,
                        'active'                    : item.node.active,
                        'nodes.$.name'              : item.nodes.name,
                        'nodes.$.active'            : item.nodes.active,
                        'nodes.$.preference.name1'  : item.nodes.preference.name1,
                        'nodes.$.preference.name2'  : item.nodes.preference.name2,
                        'nodes.$.preference.name3'  : item.nodes.preference.name3,
                        'nodes.$.preference.name4'  : item.nodes.preference.name4,
                        'nodes.$.preference.name5'  : item.nodes.preference.name5
                    ]

                    def haveItem = node.sku.find { it == item.sku }, inc = [:]
                    if(!haveItem) {
                        inc << ['itemcount': 1, 'nodes.$.itemcount': 1]
                    }

                    db.nodes.update(['nodeid': item.node.nodeid, 'nodes.nodeid': item.nodes.nodeid],[
                        '$set' : set,
                        '$inc' : inc
                    ])
                }
                else { // insert new subnode
                    db.nodes.update(['nodeid': item.node.nodeid],[
                        '$push': ['nodes': item.nodes << ['itemcount': 1]],
                        '$inc' : ['itemcount': 1]
                    ])
                }
            }
        }
        catch(error) {
            println "MongoService:updateNode: $error"
        }
    }







}

